/**
 * 
 */
package bingo.validation.validator;

import bingo.validation.ValidationException;
import bingo.validation.ValidationResult;
import bingo.validation.annotations.AnnotationValidator;
import bingo.validation.annotations.Length;
import bingo.validation.convert.StringConverter;

/**
 * 对长度进行验证的校验类,null被认为不通过校验
 */
public class LengthValidator extends AnnotationValidator<Length> {
	
	private int min;
	
	private int max;
	
	public LengthValidator(){
		this.setMessage("{name}的长度必须在{min}和{max}之间");
	}
	
	@Override
	public void initialize(Length check) {
		super.initialize(check);
		
		this.min = check.min();
		this.max = check.max();
	}

	/* (non-Javadoc)
	 * @see bingo.validation.annotations.AnnotationValidator#doValidate(java.lang.Object, java.lang.Object)
	 */
	@Override
	protected ValidationResult doValidate(Object objectToValidate, Object valueToValidate) throws ValidationException {

		if(null != valueToValidate){
			String value = StringConverter.instance.convert(valueToValidate);
			
			if(value.length() >= min && value.length() <= max){
				return ValidationResult.pass();
			}
		}
		
		return ValidationResult.notPass(formatMessage());
	}

}
